package com.budwk.app.dfxyWechatMP;

import com.alibaba.fastjson.JSONObject;
import com.budwk.app.util.HttpUtils;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;

/**
 * @author ZY.Wang
 * @since 2023/7/20
 * <p>
 * 这个是用来生成东方祥云小程序链接的工具类
 */
public class DfxyWeChatMPUtils {

    public static String generatedDfxyMiniProgramUrl(String path) {

        if (StringUtils.isBlank(path)) path = "/pagesIndex/index";

        // 获取accessToken
        Map<String, Object> accessTokenMap = Maps.newHashMap();
        accessTokenMap.put("grant_type", "client_credential");
        accessTokenMap.put("appid", "wx03d69fde959604e1");
        accessTokenMap.put("secret", "31d770915c6550b8db12c7a4448ef562");

        Map<String, String> headMap = Maps.newHashMap();
        headMap.put("Content-Type", "application/json");
        headMap.put("Accept", "*/*");
        headMap.put("Connection", "keep-alive");
        String accessTokenResponseStr = HttpUtils.getRequest("https://api.weixin.qq.com/cgi-bin/token", headMap, accessTokenMap);
        if (StringUtils.isBlank(accessTokenResponseStr)) return null;

        JSONObject jsonObject = JSONObject.parseObject(accessTokenResponseStr);
        String token = jsonObject.getString("access_token");

        if (StringUtils.isBlank(token)) return null;

        Map<String, Object> urlParamMap = Maps.newHashMap();
        urlParamMap.put("path", path);
        String urlResponseStr = HttpUtils.postRequestWithJson("https://api.weixin.qq.com/wxa/generate_urllink?access_token=" + token, null, urlParamMap);
        if (StringUtils.isBlank(urlResponseStr)) return null;

        JSONObject urlJsonObj = JSONObject.parseObject(urlResponseStr);
        return urlJsonObj.getString("url_link");
    }
}
